package xyz.labmem.app.tray

import javafx.event.EventHandler
import javafx.scene.Scene
import javafx.scene.control.Button
import javafx.scene.layout.Pane
import javafx.scene.layout.VBox
import javafx.scene.paint.Color
import javafx.stage.Popup
import javafx.stage.Stage
import javafx.stage.StageStyle
import xyz.labmem.app.main.MainStage
import xyz.labmem.app.unit.MsgUnit
import xyz.labmem.app.util.close
import xyz.labmem.util.viewRun


/**
 * @author       : ltty
 * @description  :
 * @createDate   : 2025/5/27
 */
class TrayMenuManager {
    private val popupMenu: Popup = Popup()
    private val popupStage = Stage()
    private val menuBox = VBox().apply {
        style = "-fx-background-color: white; -fx-border-color: #ccc; -fx-border-width: 1px;"
    }

    init {
        // 1. 创建透明JavaFX Stage
        popupStage.initStyle(StageStyle.UTILITY)
        popupStage.opacity = 0.0
        popupStage.width = 1.0
        popupStage.height = 1.0

        // 创建空场景
        val popupScene = Scene(Pane())
        popupScene.fill = Color.TRANSPARENT
        popupStage.scene = popupScene

        // 显示但不获取焦点
        popupStage.show()
        popupStage.isAlwaysOnTop = true
        popupStage.toBack()

        // 配置Popup自动隐藏
        popupMenu.isAutoHide = true
        popupMenu.isHideOnEscape = true

        // 创建菜单项
        val exitBtn = Button("退出程序").apply {
            onAction = EventHandler {
                viewRun {
                    MainStage.confirmDialog("关闭LIPX", "那么明天见？") {
                        Thread {
                            MsgUnit.getMsgUnit().showMsg("再见~周卡")
                            Thread.sleep(1000)
                            MainStage.self?.scene?.window?.close()
                        }.start()
                        true
                    }
                    popupMenu.hide()
                }
            }
        }

        menuBox.children.add(exitBtn)
        popupMenu.content.add(menuBox)
    }

    fun showMenu(screenX: Double, screenY: Double) {
        if (!popupMenu.isShowing) {
            // 确保Popup显示在正确位置
            popupMenu.show(popupStage, screenX, screenY - menuBox.prefHeight(-1.0))
        } else
            popupMenu.hide()
    }
}